import { join } from 'node:path';

import { defaultConfig as defaultConfigFile, FangFile } from '../file';
import type { Config as ConfigFile } from '../file';
import type { RurDevCallback, ConfigCallback } from '../com';

type ObjStr = {
	[key: string]: string;
};

export interface Config extends ConfigFile {
	/**
	 * 输出文件目录
	 */
	files?: ObjStr;
}

export const defaultConfig: Config = Object.assign({}, defaultConfigFile, {
	name: 'pars',
	read: true,
	files: {},
});

export class FangPars extends FangFile {
	constructor(config?: Config, callback?: ConfigCallback) {
		super();
		this.config = {};
		this._configCallback = callback;
		this._defaultConfig = defaultConfig;
		this.initConfig(config || this.config);
	}
	/**
	 * 获取输出地址方法
	 * @param gene
	 * @returns
	 */
	getDefaultGene(name: string, url: string, _wj?: string) {
		const obj = this.getGeneObj(url, name, this.config.outDir);
		return join(obj.catalogue, obj.name + '.' + obj.suffix);
	}
	getFiles(key?: string) {
		if (key) {
			return this.config.files[key];
		}
		return this.config.files;
	}
	getImps(text: string): string[] {
		return [];
	}
	getDefaultFileSet(
		//文件名称
		name: string,
		//文件目录
		url: string,
		//文件内容
		text: string,
		// 文件名称，没有后缀的
		wjm?: string,
		// 引用路径
		imp?: string,
	) {
		const key = join(url, name);
		this.config.files[key] = {
			//文件名称
			name,
			//文件目录
			url,
			//文件内容
			text,
			// 文件名称，没有后缀的
			wjm,
			// 引用路径
			imp,
			pars: this.getImps(text),
		};
		return [];
	}
}
export async function runDev(
	config?: Config,
	configCallback?: ConfigCallback,
	callback?: (fang: FangPars) => void,
) {
	const fang = new FangPars(config);
	await fang.runDev(() => {}, configCallback);
	if (callback) {
		callback(fang);
	}
}
